package com.frogs.ucenter.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.util.ApplicablePlatformEnum;
import com.frogs.system.util.PromotionApplicablePlatformEnum;
import com.frogs.system.util.ShoppingCartStatusEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.service.ShoppingCartService;

@Service("shoppingCartService")
public class ShoppingCartServiceImpl extends GoodsBaseServiceImpl implements ShoppingCartService {
	
	private static Logger log = LoggerFactory.getLogger(ShoppingCartServiceImpl.class);

	/**
	 * 获取购物车列表
	 * @param userId
	 * @param applicablePlatformId平台id {@link ApplicablePlatformEnum}
	 * @param pageNo
	 * @param pageSize
	 * 
	 * @return
	 */
	private JSONObject getPageList(Integer userId,
			Integer applicablePlatformId , Integer pageNo,Integer pageSize )  throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_SHOPPING_CART_LIST");
		
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(),userId.toString(),
								ApiUrlParamEnum.pageNo.getParamName(),pageNo.toString(),
								ApiUrlParamEnum.pageSize.getParamName() , pageSize.toString(),
								ApiUrlParamEnum.applicablePlatformId.getParamName() , applicablePlatformId.toString(),
								
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[getPageList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("获取购物车列表接口异常！");
		}
		return result;
	}

	@Override
	public JSONObject deleteShoppingCart(Integer userId, Integer id,Integer applicablePlatformId)  throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_SHOPPING_CART_DELETE");
		
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(),userId.toString(),
				ApiUrlParamEnum.applicablePlatformId.getParamName(),applicablePlatformId.toString(),
				ApiUrlParamEnum.status.getParamName(),ShoppingCartStatusEnum.STATUS_MANUAL_DELETE.getId()+"",
				ApiUrlParamEnum.ids.getParamName(),id.toString(),
				
				
		};
		
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[deleteShoppingCart] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("删除购物车列表接口异常！");
		}
		return result;
	}

	@Override
	public JSONObject updateShoppingCart(Integer userId, Integer id, Integer amount) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	/**
	 * 获取购物车列表(关联商品信息)
	 * @param userId
	 * @param applicablePlatformId平台id {@link ApplicablePlatformEnum}
	 * @param pageNo
	 * @param pageSize
	 */
	public List<Map<String, Object>> getShoppingCartList(Integer userId,
			Integer applicablePlatformId , Integer pageNo,Integer pageSize )  throws Exception {
		
    	List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		JSONObject cartJson = this.getPageList(userId,applicablePlatformId,pageNo,pageSize);
		if(null != cartJson && cartJson.getJSONObject("response").containsKey("list")) {
	    	JSONArray listJSONArray = cartJson.getJSONObject("response").getJSONArray("list");
	    	if (listJSONArray != null && listJSONArray.size() > 0) {
	    		Map<Integer, JSONObject> goodsMap  = this.getGoodsMap(listJSONArray);
	    		result.addAll(this.mergeShoppingCartAndGoods(listJSONArray, goodsMap));
	    	}
		}
		return result;
	}
    
    /**
     * 购物车信息合并商品信息
     * @param jsonArray
     * @param goodsMap
     * @return
     */
    private List<Map<String,Object>> mergeShoppingCartAndGoods (JSONArray jsonArray,Map<Integer,JSONObject> goodsMap)  throws Exception {
    	List<Map<String,Object>> shoppingCartList = new ArrayList<Map<String,Object>>();
    	
		for(int j = 0; j<jsonArray.size(); j++) {
			JSONObject cartInfoJSONObject = jsonArray.getJSONObject(j);
			Map<String,Object> cartInfoMapObject= JSON.toJavaObject(cartInfoJSONObject, Map.class);
			JSONObject goodsJSONObject = goodsMap.get(cartInfoJSONObject.getInteger("mealId"));
			if(goodsJSONObject != null){
				cartInfoMapObject.put("coverImgPath", goodsJSONObject.get("mealCoverImage"));
				cartInfoMapObject.put("title",goodsJSONObject.getString("mealName") );
				cartInfoMapObject.put("realPrice",goodsJSONObject.getString("mealPrice") );
				log.info("func[mergeShoppingCartAndGoods]  add " + cartInfoMapObject);
				shoppingCartList.add(cartInfoMapObject);
			}
		}
		return shoppingCartList;
    }
    
    /**
     * 根据购物车中的商品id，查询商品信息
     * @param jsonArray
     * @return
     */
    @Deprecated
    private Map<Integer,JSONObject> getGoodsMapDel(String skuIds)  throws Exception {
    	
    	JSONObject goodsJson = null;//super.getByIds(skuIds);
    	JSONArray goodsArrayJson = goodsJson.getJSONObject("response").getJSONArray("list");
    	Map<Integer,JSONObject> goodsMap = new HashMap<Integer,JSONObject>();
    	if(null != goodsArrayJson ) {
    		for(Object goodsObject:goodsArrayJson){
    			JSONObject goods = (JSONObject)goodsObject;
    			goodsMap.put(goods.getInteger("productId"), goods);
    		}
		}
    	
    	return  goodsMap;
    }
    
    /**
     * 合并购物车
     */
    @Override
    public void mergeShoppingCart(Integer userId, String userTraceId)  throws Exception {
    	ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_SHOPPING_CART_MERGE");
		
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
								ApiUrlParamEnum.userTraceId.getParamName(), userTraceId,
								};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[mergeShoppingCart] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("合并购物车接口异常！");
		}
    }
    
    /**
     * 合并购物车
     */
    @Override
    public JSONObject sumShoppingCart(Integer userId)  throws Exception {
    	ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_SHOPPING_CART_SUM");
    	
    	String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
    			};
    	String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
    	JSONObject result = null;
    	try{
    		result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
    		if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
    			throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
    	} catch (IllegalStateException e) {
    		log.error("func[sumShoppingCart] url[{}] params[{}] exception[{} - {}] desc[fail]",
    				new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
    	}catch(Exception e){
    		throw new Exception("合并购物车接口异常！");
    	}
    	
    	return result;
    }

	@Override
	public JSONObject mergeShoppingCartSnap(Integer userId, String userTraceId)
			throws Exception {
		
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("PROMOTION_SHOPPINGCART_SNAP_MERGE");
		
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
								ApiUrlParamEnum.userTraceId.getParamName(), userTraceId};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName()))
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[mergeShoppingCartSnap] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}catch(Exception e){
			throw new Exception("合并购物车快照接口异常！");
		}
		return null;
	}

	/**
	 * 秒杀回滚
	 * 
	 * 先判断商品是否参与秒杀活动
	 * （是则调用回滚接口，否则结束返回）
	 */
	@Override
	public void rockBackSeckillRestriction(Integer userId, Integer mealId, Integer skNum) throws Exception {
		try {
			String targerId = this.showGoodsSeckill(mealId, PromotionApplicablePlatformEnum.NEW_MALL.getId());
			if(StringUtil.isEmpty(targerId)) {//该商品没有参与秒杀活动不需要回滚
				return ;
			}
			this.cancelSeckillRestriction(userId, mealId, targerId, skNum, PromotionApplicablePlatformEnum.NEW_MALL.getId());
		} catch (Exception e) {
			log.error("请求处理失败" + e.getMessage());
		}
	}

	/**
	 * 获取商品参与秒杀的活动
	 */
	@Override
	public String showGoodsSeckill(Integer mealId, Integer applicablePlatformId) throws Exception {
		ApiUrl apiUrl = this.buildPromotionApiBaseUrl("PROMOTION_SECKILL_SHOWBYGOODS");
		String[] otherParams = {ApiUrlParamEnum.mealIds.getParamName(), mealId.toString(),//209
								ApiUrlParamEnum.applicablePlatformId.getParamName() , "" + PromotionApplicablePlatformEnum.NEW_MALL.getId()};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		JSONObject result = null;
		try {
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if(ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				JSONObject info = result.getJSONObject("response").getJSONObject("info");
				if(info != null) {
					return info.getJSONObject(mealId.toString()).getString("id");
				}
				
				log.info("func[showGoodsSeckill],返回成功但没有符合商品的秒杀活动");
				return null;
			} else {
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			}
		} catch (IllegalStateException e) {
			log.error("func[showGoodsSeckill] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e) {
			throw new Exception("获取商品秒杀限购活动接口异常！");
		}
		return null;
	}
	
	/**
	 * 取消秒杀
	 */
	@Override
	public void cancelSeckillRestriction(Integer userId, Integer mealId, String targerId, Integer skNum, Integer applicablePlatformId) throws Exception {
		ApiUrl apiUrl = this.buildPromotionApiBaseUrl("PROMOTION_SECKILL_CANCEL");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				ApiUrlParamEnum.mealId.getParamName(), mealId.toString(),
				ApiUrlParamEnum.targetId.getParamName(), targerId,//"41"
				ApiUrlParamEnum.num.getParamName(), skNum.toString(),
				ApiUrlParamEnum.applicablePlatformId.getParamName() , "" + PromotionApplicablePlatformEnum.NEW_MALL.getId()};
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		JSONObject result = null;
		try {
			result = (JSONObject) this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() != result.getJSONObject("response")
					.getIntValue(ResultParamEnum.code.getParamName())) 
				throw new IllegalStateException(result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
			
			log.info("func[cancelSeckillRestriction], " + result.getJSONObject("response").getString(ResultParamEnum.tip.getParamName()));
		} catch (IllegalStateException e) {
			log.error("func[cancelSeckillRestriction] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch (Exception e) {
			throw new Exception("取消秒杀限购接口异常！");
		}
	}
	
}
